package com.qyl.sever_rpc.client;

import com.qyl.sever_rpc.pojo.Args2;
import com.qyl.sever_rpc.pojo.Constant;
import com.qyl.sever_rpc.util.SerializeUtil2;

import java.io.*;
import java.net.Socket;

public class Client2 implements MathInterface {

    public static final String HOST = "127.0.0.1";
    public static final Integer PORT = 9000;
    @Override
    public Integer add(Integer arg1, Integer arg2) {
        return invoke(new Args2(arg1, arg2, Constant.ADD));
    }

    @Override
    public Integer sub(Integer arg1, Integer arg2) {
        return null;
    }

    private Integer invoke(Args2 args){
        Integer res = null;
        try {
            String str = SerializeUtil2.serializeArgs(args);
            res = Integer.parseInt(sendDataToSocket(str));
        } catch (Exception e) {
            e.printStackTrace();
        }
//        System.out.println(getSerializeArgs(str).getArg1() + "   "+getSerializeArgs(str).getArg2());
        return res;
    }



    // 连结服务
    private String sendDataToSocket(String data){
        String res = "";
        try {
            Socket socket = new Socket("127.0.0.1", 9000);
            // 向服务端程序发送数据
            OutputStream ops = socket.getOutputStream();
            OutputStreamWriter opsw = new OutputStreamWriter(ops);
            BufferedWriter bw = new BufferedWriter(opsw);
            bw.write(data+"\r\n\r\n"); // \n不能省，否则readline读不出来
            bw.flush();

            // 从服务端程序接收数据
            InputStream ips = socket.getInputStream();
            InputStreamReader ipsr = new InputStreamReader(ips);
            String s = "";
            BufferedReader br = new BufferedReader(ipsr);
//            System.out.println("2222"+br.lines().collect(Collectors.toList()).size());
            if((s = br.readLine()) != null) {
                System.out.println(s);
                res += s;
            }
//            int newread = 0;
//            int totalread = 0;
//            int contentLength = Integer.parseInt(headers.get("content-length"));
//            byte[] bytes = new byte[contentLength];
//            while (totalread < contentLength) {
//                newread = bufferedInputStream.read(bytes, totalread, contentLength - totalread);
//                totalread += newread;
//            }

            socket.close();
//            System.out.println(args[0] + "已连接成功!");
        }
        catch (Exception e) {
            System.err.println("exception：" + e.getMessage());
        }
        return res;
    }

    public static void main(String[] args) throws Exception {
        Client2 c = new Client2();
//        System.out.println(c.invoke(1,2));
    }
}
